package unq.tpi.persistencia.performanceEj.daos;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.IntegerType;
import org.hibernate.type.Type;

import unq.tpi.persistencia.performanceEj.model.Employee;
import unq.tpi.persistencia.performanceEj.model.Salary;
import unq.tpi.persistencia.util.SessionManager;


public class EmployeeDAO {

	public Employee getByName(final String name, final String lastName) {
		Session session = SessionManager.getSession();
		Employee emp = (Employee) session.createCriteria(Employee.class)
			.add(Restrictions.eq("firstName", name))
			.add(Restrictions.eq("lastName", lastName))
			.uniqueResult();
		session = SessionManager.getSession();

		return emp;
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getAll() {
		Session session = SessionManager.getSession();
		return session.createCriteria(Employee.class).list();
	}

	public Employee getByCode(int id) {
		Session session = SessionManager.getSession();
		return (Employee) session.load(Employee.class, id);
	}

	public List<Employee> getAllWithOrder(int n){
		Session session = SessionManager.getSession();
		@SuppressWarnings("unchecked")
		List<Salary>s = session.createCriteria(Salary.class)
		.addOrder(Order.desc("amount"))
		.setMaxResults(n)
		.list();
		List<Employee> emp = new ArrayList<Employee>();
		for(int i = 0; i < n; i++){
			emp.add(s.get(i).getEmployee());
		}
		
		return emp;
	}
	
	public double getSalary(Employee id){
		Session session = SessionManager.getSession();
		@SuppressWarnings("unchecked")
		List<Salary> s= session.createCriteria(Salary.class)
				.add(Restrictions.eq("employee",id))
				.addOrder(Order.desc("amount"))
				.setMaxResults(2)
				.list();
		return s.get(0).getAmount();
		
	}
	
	public String getTitle(int id){
		Session session = SessionManager.getSession();
		
		SimpleDateFormat textFormat = new SimpleDateFormat("yyyy-MM-dd");
		String paramDateAsString = "9999-01-01";
		Date myDate = null;

		try {
			myDate = textFormat.parse(paramDateAsString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return (String) session.createCriteria(Employee.class)
				.add(Restrictions.eq("id", id))
				.createAlias("titles", "tit")
				.add(Restrictions.sqlRestriction("{alias}.emp_no = ? and {alias}.to_date = '9999-01-01'", id, IntegerType.INSTANCE))
				.setProjection(Projections.property("tit"))
				.uniqueResult();
	} 
}
